import React from 'react';
import { Spin, Space, Button, DatePicker, Row, Col } from 'antd';
import moment from 'moment';

import { TRMessage } from '#/components';
import { UploadOutlined } from '#/utils/antdIcons';
import { useTRState, TjSelect } from '@/pages/ETrade/components';
import { TIME_96 } from '@/pages/ETrade/components/helper';
import { export_json_to_excel } from '@/utils/fileExport.js';

import { getPriceDifferenceDistributionStatistical } from '../services';
import { getSeries1, getSeries2, dataTypes } from './helper';
import { Chart1, Chart2 } from './charts';
import styles from './index.less';

const defaultForm = (power) => {
  const stations = power?.[0]?.children || [];
  const dates = [moment().add(-7, 'days'), moment().add(-1, 'days')];
  return {
    stations,
    dates,
    provinceId: power?.[0]?.provinceId || null,
    marketId: power?.[0]?.value || null,
    stationItem: stations?.[0] || null,
  };
};
export default ({ power, buttonPermissions }) => {
  const exportKey = 'SpotPriceDiffForecastStatistics-export';
  const [state, setState] = useTRState({
    canExport: buttonPermissions.some((item) => item.menuCode === exportKey),
    // 表单
    ...defaultForm(power),
    // 数据
    series1: null,
    series2: null,
    loading: true,
    exporter: {}, // 导出文件名称
  });

  React.useEffect(() => {
    _onFinish();
  }, []);

  const fetch = async (params) => {
    setState({ loading: true });
    // ！顺序勿动,向后添加
    const res = await getPriceDifferenceDistributionStatistical(params);
    const series1 = getSeries1(res?.priceDifferenceDistributionMap);
    const series2 = getSeries2(res?.priceDifferenceImpactStatisticalMap);
    setState({
      series1,
      series2,
      loading: false,
    });
  };

  /** methods */
  const onChangeRegion = (region) => {
    // 改变省份
    const provinceId = region.provinceId;
    const marketId = region.value;
    const stations = region?.children || [];
    const stationItem = stations?.[0] || null;
    setState({
      provinceId,
      marketId,
      stations,
      stationItem,
    });
  };

  const _onFinish = () => {
    // 查询
    const { provinceId, stationItem, dates } = state;
    const formValues = {
      provinceId,
      stationId: stationItem.value,
      startDate: dates[0].format('YYYY-MM-DD'),
      endDate: dates[1].format('YYYY-MM-DD'),
    };
    setState({
      exporter: {
        staitonName: stationItem.label,
        dateRange: `${dates[0].format('YYYYMMDD')}-${dates[1].format('YYYYMMDD')}`,
      },
    });
    fetch(formValues);
  };

  const _onReset = () => {
    // 重置
    const _def = defaultForm(power);
    state.dates = _def.dates;
    state.provinceId = _def.provinceId;
    state.marketId = _def.marketId;
    state.stationItem = _def.stationItem;
    setState({
      ..._def,
    });
    _onFinish();
  };

  const _onExport = () => {
    // 导出
    if (!state.canExport) return TRMessage.info('请联系管理员获取相关权限');
    const { staitonName, dateRange } = state.exporter;
    const s1 = state.series1 || {};
    const s2 = state.series2 || [];
    const params = {
      filename: `${staitonName}-${dateRange}-价差统计`,
      header: [`${staitonName} 历史出清价差分布统计`, dateRange],
      data: [
        ['日期', ...TIME_96],
        ...dataTypes.map(({ value, label }) => [label, ...(s1?.[value] || [])]),
        [],
        [`${staitonName} 市场供需对价差影响力统计`, dateRange],
        ['日期', ...TIME_96],
        ...s2.map(({ name, data }) => [name, ...data]),
      ],
      autoWidth: false,
    };
    export_json_to_excel(params);
  };

  /** render */
  const _renderMain = () => {
    if (state.loading) return null;
    return (
      <Row gutter={[24, 24]}>
        <Col span={12}>
          <Chart1 series={state.series1} />
        </Col>
        <Col span={12}>
          <Chart2 series={state.series2} />
        </Col>
      </Row>
    );
  };

  return (
    <Spin spinning={state.loading}>
      <div className={styles.head}>
        <Space size={16} wrap>
          <TjSelect
            style={{ width: 200 }}
            value={state.marketId}
            options={power}
            showSearch
            onChange={(v, opt) => onChangeRegion(opt)}
          />
          <TjSelect
            style={{ width: 200 }}
            value={state.stationItem?.value}
            options={state.stations}
            showSearch
            onChange={(v, stationItem) => setState({ stationItem })}
          />
          <DatePicker.RangePicker
            style={{ width: 260 }}
            value={state.dates}
            separator="-"
            format={'YYYYMMDD'}
            allowClear={false}
            onChange={(dates) => setState({ dates })}
            getPopupContainer={(e) => e.parentNode}
          />
          <Space size={16}>
            <Button style={{ width: 98, height: 32 }} type="primary" onClick={_onFinish}>
              查询
            </Button>
            <Button style={{ width: 98, height: 32 }} ghost onClick={_onReset}>
              重置
            </Button>
            <Button type="link" icon={<UploadOutlined />} onClick={_onExport}>
              导出
            </Button>
          </Space>
        </Space>
      </div>
      <div className={styles.main}>{_renderMain()}</div>
    </Spin>
  );
};
